package function.now;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Random;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import boot.Boot;

import tool.FileConnectionUtils;
import tool.Log;
import tool.Path;
import tool.Properties;
import db.DBReader;
import db.Mp3DBRecord;
import files.Files;
import function.Mp3File;

public class NowManager {

	public static Mp3File selectNewMp3FromBoot() {
		int bootSize = getBOOTSize();
		int linkNumber = FileConnectionUtils.getLinkNumber();
		int index = new Random(Calendar.getInstance().getTime().getTime())
				.nextInt(bootSize - linkNumber);
		
		DBReader dbReader = new DBReader(Files.BOOT_ROOT + "/BOOT_FOLDER.db");
		NowDBListener listener = new NowDBListener(index, dbReader);
		dbReader.addListener(listener);
		dbReader.readDB();
		Mp3DBRecord record = listener.getRecord();
		
		Log.log("Selection : ");
		Log.log(record.getTitle());
		
		createLink(record);
		
		return record.getMp3File();
	}

	private static void createLink(Mp3DBRecord record) {
		
		try {
			FileConnection fc = (FileConnection) Connector.open(
					Path.NOW + "/" + record.getTitle() + ".link");
			fc.create();
			OutputStream fos = fc.openOutputStream();
			
			String line = makeLine(record);
			
			fos.write(line.getBytes());
			fos.close();
			fc.close();
		} catch (IOException e) {
			Boot.alertException(e, new NowManager(), "createLink()");
		}
	}

	private static String makeLine(Mp3DBRecord record) {

		return record.getTitle() + "\r\n\t" + record.getArtist() + "\r\n\t"
				+ record.getFolder() + "\r\n\t" + record.getRating();
	}

	private static int getBOOTSize() {
		Properties bootProps = new Properties(Files.BOOT_ROOT
				+ "/DBProperties/Boot.db.properties");
		return Integer.parseInt(bootProps.getProperty("bootSize"));
	}

}
